<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购到货单编号" prop="arrivedCode">
              <el-input
                v-model="queryParams.arrivedCode"
                placeholder="请输入采购到货单编号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称" prop="vendorName">
              <el-input
                v-model="queryParams.vendorName"
                placeholder="请输入供应商名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="contact">
              <el-input
                v-model="queryParams.contact"
                placeholder="请输入联系人"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="联系人电话" prop="contactTel">
              <el-input
                v-model="queryParams.contactTel"
                placeholder="请输入联系人电话"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到货日期" prop="params">
              <el-date-picker
                clearable
                v-model="queryParams.params"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                placeholder="请选择到货日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['cg:arrived:add']"
          >新增
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="arrivedList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="采购到货单编号" align="center" prop="arrivedCode">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleInfoView(scope.row)"
              v-hasPermi="['cg:arrived:query']"
              v-if="scope.row.isReturn==='Y'"
              style="color: red"
            >{{ scope.row.arrivedCode }}
            </el-button>
            <el-button
              type="text"
              @click="handleInfoView(scope.row)"
              v-hasPermi="['cg:arrived:query']"
              v-else
            >{{ scope.row.arrivedCode }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="采购到货日期" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供应商编码" align="center" prop="vendorCode"/>
        <el-table-column label="供应商名称" align="center" prop="vendorName"/>
        <el-table-column label="联系人" align="center" prop="contact"/>
        <el-table-column label="联系人-电话" align="center" prop="contactTel"/>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding">
          <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['cg:arrived:edit']"
                v-show="scope.row.status==='PREPARE'&& scope.row.isReturn!='Y'"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['cg:arrived:remove']"
                v-show="scope.row.status==='PREPARE' && scope.row.isReturn!='Y'"
              >删除
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-s-check"
                @click="handleConfirm(scope.row)"
                v-hasPermi="['cg:arrived:query']"
                v-show="scope.row.status==='PREPARE'"
              >确认
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-upload2"
                @click="handleRecpt(scope.row)"
                v-hasPermi="['cg:arrived:applyRecpt']"
                v-show="scope.row.status==='CONFIRMED'&& scope.row.showRecept"
              >申请入库
              </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改采购管理-采购到货单主对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购到货单编号" prop="arrivedCode">
              <el-input v-model="form.arrivedCode" placeholder="请输入采购到货单编号" :readonly="optType!='add'"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商">
                <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search" :disabled="form.isReturn==='Y'"></el-button>
              </el-input>
              <VendorSelect ref="vendorSelect" @onSelected="onVendorSelected"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系人" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人-电话" prop="contactTel">
              <el-input v-model="form.contactTel" placeholder="请输入联系人-电话" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">到货单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddCgPurchaseOrderArrivedLine"
                       v-if="showSaveButton"
                       v-show="form.vendorId && !(form.isReturn==='Y')">
              添加
            </el-button>
          </el-col>
        </el-row>
        <el-table border :data="cgPurchaseOrderArrivedLineList" :row-class-name="rowCgPurchaseOrderArrivedLineIndex"
                  ref="cgPurchaseOrderArrivedLine">
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="采购计划编号" align="center" prop="planNumber" width="150"/>
          <el-table-column label="采购订单编号" align="center" prop="orderCode" width="150"/>
          <el-table-column label="采购员姓名" align="center" prop="buyer" width="150"/>
          <el-table-column label="物料编号" align="center" prop="itemCode" width="150"/>
          <el-table-column label="物料名称" align="center" prop="itemName" width="150"/>
          <el-table-column label="规格型号" align="center" prop="specification" width="150"/>
          <el-table-column label="单位" align="center" prop="unitOfMeasure" width="150"/>
          <el-table-column label="物料分类名称" align="center" prop="itemTypeName" width="150"/>
          <el-table-column
            v-for="col in columnsConfig"
            :key="col.prop"
            :label="col.label"
            :prop="col.prop"
            :width="col.width"
            :align="col.align"
            v-if="col.show">
          </el-table-column>
          <el-table-column label="客户" align="center" prop="clientName" width="150"/>
          <el-table-column label="应到货数量" align="center" prop="notArrivedQuantity" width="150"  v-if="!(form.isReturn==='Y')" >
            <template slot-scope="scope">
              <span >{{scope.row.notArrivedQuantity}}</span>
            </template>
          </el-table-column>
          <el-table-column label="到货数量" align="center" prop="arrivedQuantity" width="200" >
            <template slot-scope="scope">
              <span v-if="(form.isReturn==='Y')">{{scope.row.arrivedQuantity}}</span>
<!--              <el-input-number v-model="scope.row.arrivedQuantity" :precision="2" :step="1.00" size="small" :min="1"
                               :max="scope.row.notArrivedQuantity" v-if="!(form.isReturn==='Y')"></el-input-number>-->
              <el-input-number v-model="scope.row.arrivedQuantity" :precision="2" :step="1.00" size="small" :min="1"
                                v-if="!(form.isReturn==='Y')"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="price" width="200" >
            <template slot-scope="scope">
              <el-span v-if="(form.isReturn==='Y')">{{scope.row.price}}</el-span>
              <el-input-number v-model="scope.row.price" :precision="2" :step="1.00" size="small" :min="0.01"
                               v-if="!(form.isReturn==='Y')"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="是否需要质检" align="center" prop="iqcCheck" width="150"  v-if="!(form.isReturn==='Y')">
            <template slot-scope="scope">
              <el-select v-model="scope.row.iqcCheck">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" v-if="!(form.isReturn==='Y')">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="deleteGoodsList(scope.row)"
              >删除商品
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="showSaveButton">保 存</el-button>
        <el-button type="success" @click="confirmForm" v-if="showConfirmButton && form.id">确 认</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <!--选择商品信息弹出框-->
      <ItemSelect ref="itemSelect" :vendorId="form.vendorId" :arrivedQuantity="arrivedQuantity" @onSelected="onItemSelected"
                  v-if="form.vendorId"></ItemSelect>
    </el-dialog>
    <InfoView ref="infoView"></InfoView>
  </div>
</template>

<script>
import {listArrived, getArrived, delArrived, addArrived, updateArrived,applyRecpt} from "@/api/mes/cg/arrived";
import {genCode} from "@/api/system/autocode/rule";
import VendorSelect from "@/components/vendorSelect/single.vue";
import ItemSelect from "@/views/mes/cg/arrived/itemSelect.vue";
import InfoView from "@/views/mes/cg/arrived/infoView.vue";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";

export default {
  name: "Arrived",
  components: {ItemSelect, VendorSelect, InfoView},
  dicts: ['sys_yes_no', 'mes_order_status'],
  data() {
    return {
      arrivedQuantity:{},
      optType: undefined,
      showSaveButton: true,
      showConfirmButton: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedCgPurchaseOrderArrivedLine: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购管理-采购到货单主表格数据
      arrivedList: [],
      // 采购管理-采购到货单明细表格数据
      cgPurchaseOrderArrivedLineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        arrivedCode: null,
        vendorName: null,
        contact: null,
        contactTel: null,
        params: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        arrivedCode: [
          {required: true, message: "采购到货单编号不能为空", trigger: "blur"}
        ],
        vendorName: [
          {required: true, message: "请选择供应商", trigger: "blur"}
        ],
      },
      columnsConfig:[],
    };
  },
  created() {
    this.getList();
    this.getItemBase();
  },
  watch: {
    'form.vendorId'(newVal, oldVal) {
      if (oldVal === null) return;
      if (newVal !== oldVal) {
        this.cgPurchaseOrderArrivedLineList = [];
      }
    }
  },
  methods: {
    /** 查询采购管理-采购到货单主列表 */
    getList() {
      const query = {...this.queryParams};
      if (query.params && query.params.length === 2) {
        query.params = {
          beginTime: query.params[0],
          endTime: query.params[1]
        };
      } else {
        query.params = null;
      }
      this.loading = true;
      listArrived(query).then(response => {
        this.arrivedList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.arrivedQuantity={};
      this.form = {
        id: null,
        arrivedCode: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        contact: null,
        contactTel: null,
        remarks: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        status: 'PREPARE',
        isReturn: 'N',
      };
      this.cgPurchaseOrderArrivedLineList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.showSaveButton = true;
      this.showConfirmButton = false;
      this.open = true;
      this.optType = 'add';
      this.title = "添加采购到货单";
      this.handleAutoGenChange();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.showSaveButton = true;
      this.showConfirmButton = false;
      const id = row.id || this.ids
      getArrived(id).then(response => {
        this.form = response.data;
        this.cgPurchaseOrderArrivedLineList = response.data.cgPurchaseOrderArrivedLineList;
        this.cgPurchaseOrderArrivedLineList.forEach(item => {
          this.arrivedQuantity[item.orderDetailId]= item.arrivedQuantity;
        })
        this.open = true;
        this.title = "修改采购到货单";
      });
    },
    handleInfoView(row) {
      this.$refs.infoView.init(row.id);
    },
    /** 确认按钮操作 */
    handleConfirm(row) {
      this.reset();
      this.showSaveButton = false;
      this.showConfirmButton = true;
      const id = row.id || this.ids
      getArrived(id).then(response => {
        this.form = response.data;
        this.cgPurchaseOrderArrivedLineList = response.data.cgPurchaseOrderArrivedLineList;
        this.open = true;
        this.title = "确认采购到货单";
      });
    },
    /** 申请入库按钮操作 */
    handleRecpt(row) {
      const id = row.id || this.ids
      getArrived(id).then(response => {
        const line=response.data.cgPurchaseOrderArrivedLineList;
        for(let i=0;i<line.length;i++){
          const item = line[i];
          if (item.iqcCheck==='Y'&& !(item.iqcCode)) {
            this.$modal.msgError('到货物品未完成质检，请完成质检后操作');
            return;
          }
        }
        this.$modal.confirm('是否确认申请入库？').then(function () {
          return applyRecpt(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.cgPurchaseOrderArrivedLineList = this.cgPurchaseOrderArrivedLineList;
          //校验到货单行不能为空
          if (this.cgPurchaseOrderArrivedLineList.length == 0) {
            this.$modal.msgError("请添加到货物料信息");
            return;
          }
          if (this.form.id != null) {
            updateArrived(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
              this.cancel()
            });
          } else {
            addArrived(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
              this.form.id = response.data;
              this.cancel()
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除采购到货单？').then(function () {
        return delArrived(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 采购管理-采购到货单明细序号 */
    rowCgPurchaseOrderArrivedLineIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 采购管理-采购到货单明细添加按钮操作 */
    handleAddCgPurchaseOrderArrivedLine() {
      this.$refs.itemSelect.selectedRows1 = this.cgPurchaseOrderArrivedLineList;
      this.$refs.itemSelect.init();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('md/arrived/export', {
        ...this.queryParams
      }, `arrived_${new Date().getTime()}.xlsx`)
    },
    handleAutoGenChange() {
        genCode('CG_ITEM_ARRIVED_CODE').then(response => {
          this.form.arrivedCode = response;
        });
    },
    //供应商选择
    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
    },
    //供应商选择弹出框
    onVendorSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        if (obj.contact1 != null && obj.contact1Tel != null) {
          this.form.contact = obj.contact1;
          this.form.contactTel = obj.contact1Tel;
        } else {
          this.form.contact = obj.contact2;
          this.form.contactTel = obj.contact2Tel;
        }
      }
    },
    //物料选择弹出框
    onItemSelected(obj) {
      if (this.cgPurchaseOrderArrivedLineList && this.cgPurchaseOrderArrivedLineList.length > 0) {
        this.cgPurchaseOrderArrivedLineList.forEach((item, index) => {
          obj.find((item1) => {
            if (item.orderDetailId == item1.orderDetailId) {
              if (item.id) {
                item1.id = item.id;
              }
              item1.arrivedQuantity = item.arrivedQuantity;
              item1.iqcCheck = item.iqcCheck;
            }
          })
        })
      }
      this.cgPurchaseOrderArrivedLineList = obj;

    },
    //删除添加的商品方法
    deleteGoodsList(row) {
      this.cgPurchaseOrderArrivedLineList.splice(this.cgPurchaseOrderArrivedLineList.indexOf(row), 1);
    },
    confirmForm() {
      let that = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否确认到货单？【确认后将不能更改】').then(function () {
            that.form.status = 'CONFIRMED';
            that.submitForm();
            that.cancel();
          });
        }
      });
    }
  },
};
</script>
